<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useAnalysisStore } from '@/stores/analysisStore'

const props = defineProps({
  city: {
    type: String,
    required: true
  }
})

const analysisStore = useAnalysisStore()
const chartContainer = ref(null)
let chart = null
const loading = ref(false)

const initChart = () => {
  if (!chartContainer.value) return
  
  chart = echarts.init(chartContainer.value)
  chart.showLoading()
}

const loadData = async () => {
  if (!props.city) return
  
  loading.value = true
  try {
    const data = await analysisStore.fetchLayoutDistribution(props.city)
    renderChart(data)
  } catch (error) {
    console.error('加载户型分布数据失败:', error)
  } finally {
    loading.value = false
    if (chart) {
      chart.hideLoading()
    }
  }
}

const renderChart = (data) => {
  if (!chart) return
  
  // 颜色数组
  const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4']
  
  const option = {
    title: {
      text: `${props.city}户型分布`,
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}套 ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: data.layouts
    },
    series: [
      {
        name: '户型分布',
        type: 'pie',
        radius: '60%',
        center: ['50%', '45%'],
        data: data.layouts.map((layout, index) => {
          return {
            value: data.counts[index],
            name: layout,
            itemStyle: {
              color: colors[index % colors.length]
            }
          }
        }),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
}

const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

watch(() => props.city, () => {
  loadData()
})

onMounted(() => {
  initChart()
  loadData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 